import Axios from "axios";
import Vue from "vue";
import { Http} from "@/common/HttpClient";
import {
  Toast,
  Notify
} from "vant";
class fileUploader {
  moduleNameObj = {
      qxgl: "SDQX_SAOU", //缺陷
      yhgl: "SDYH_SAOU", //输电隐患 SDYH_SAOU
      jcgl: "SDJC_SAOU", //输电检测 SDJC_SAOU
      checkRecord: "SDXL_SAOU", //验收 SDXL_SAOU
      SignIn: "SDQD_SAOU", //签到签退
      yglz: "SDYGLZ_SAOU", //一杆六照
      tdhj: "SDTD_SAOU", //输电通道环境 SDTD_SAOU
      handyPhoto: "SDSSP_SAOU", //随手拍 SDSSP_SAOU
      "jxjh": "SDJX_SAOU", //输电检修记录
      tzgl: "SDTZ_SAOU", //输电检修记录
  };
  mIsWindowTest = false;

  async upload (data, sureBack, failBack) {
    if (data["autoShowWait"]) {
        Toast.loading({
            duration: 0,
            message: "上传中...",
            forbidClick: true,
        });
    }
    var uploadObj = Vue.prototype.$dealMsg("UPLOAD_URL") ?
        JSON.parse(Vue.prototype.$dealMsg("UPLOAD_URL")) : {};
    // -----------------穿透开发临时代码---------------------------------------------
    //获取密钥
    var uploadSaou = uploadObj.saou;
    if (data.moduleName && this.moduleNameObj[data.moduleName]) {
        data["saouKey"] = this.moduleNameObj[data.moduleName];
    }
    if (data["saouKey"] && uploadObj[data["saouKey"]]) {
        uploadSaou = uploadObj[data["saouKey"]];
    }
    let uploadUrl = uploadObj.url;
    // let uploadUrl = "http://sjtd0okmht5.epgis.com:19002/mdyj/app/oss/upload";
    if(this.mIsWindowTest){
        uploadUrl = 'http://27.196.200.157:17077' + "/app/oss/upload";//内网照片上传调试放开
    }else {
      uploadUrl = uploadUrl + "/app/oss/upload";
    }
    var isUploadFile = false
    let tformData = new FormData();
    var file = '';
    if (data["file"]) {
      file = data["file"];
      tformData.append("sftp", "shiyh");
      isUploadFile = true;
    } else if (data["base64URL"]) {
      file = this.dataURLtoFile(data["base64URL"], data["fileName"]);
      isUploadFile = false;
    }
    if (!file) {
      console.log("没有文件-------------");
      failBack && failBack();
      return
    }

   
    tformData.append("file", file);
    console.log("saouKey:" + data["saouKey"], uploadSaou, data.moduleName);
    if(this.mIsWindowTest) {
        tformData.append("secretKey", 'eGFKNjc1UWU1ZFRYU2V5TXJ3UTZaQT09');//内网照片上传调试放开
    }
    tformData.append("saou", uploadSaou);
    const platform = process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt" ? 1 : 2;
    tformData.append("platform", platform);
    const token = Http.instance().getToken();
    tformData.append("gmmsToken", token);
    if (process.env.VUE_APP_SYSTEM_ENVIRONMENT == "dlydt") {
        console.log("输电调用i国网上传文件插件");
        navigator.ajax.postFile(function(result) {
                //成功回调
                // result = {"gmmsResult":"true","businessRes":"/app/oss/download/E3634BBE5E8B4E2620230427162LPXTA229DF883567B249","gmmsMsg":"上传成功"}
                console.log("上传业务回调");
                if (data["autoShowWait"]) {
                    Toast.clear();
                }
                if(result["gmmsResult"] == "false"){
                  console.log("进入错误回调");
                  var ret = result;
                  ret["code"] = -1;
                  failBack && failBack(ret);
                }else {
                  console.log("进入成功回调");
                  var ret = result;
                  ret["url"] = ret["businessRes"];
                  sureBack && sureBack(ret);
                }
                
            },
            function(msg) {
                //失败回调
                console.log('前端失败接收数据：' + msg)
                failBack && failBack(msg);
            }, {
                //文件对象
                file: file,
                //申请的文件上传key
                saou: uploadSaou,
                //用户登录token值
                gmmsToken: token,
                isUploadFile:isUploadFile,
            });
    } else {
        console.log("Axios调用上传文件");
        console.log("Axios调用上传文件地址：" + uploadUrl);
        // uploadUrl = "http://192.168.28.59:19011/app/oss/upload";
        // // Axios.post(`${uploadUrl}`, tformData, {
        // //       headers: {
        // //           "Content-Type": "multipart/form-data",
        // //           "Access-Control-Allow-Origin": "*",
        // //           "Access-Control-Allow-Methods": "*",
        // //           "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", 
        // //       },
        // //   })

        // var config = {
        //     method: "post",
        //     url: uploadUrl,
        //     params: tformData,
        //     headers: {
        //       "Content-Type": "multipart/form-data",
        //       "Access-Control-Allow-Origin": "*",
        //       "Access-Control-Allow-Methods": "*",
        //       "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", 
        //     },
        // };
        // Axios(config).then((result) => {
        //     console.log("-----------------回调回来响应："+ JSON.stringify(result));
        //     let ret = result.data;
        //     if (data["autoShowWait"]) {
        //         Toast.clear();
        //     }
        //     ret["url"] = ret["url"];

        //     sureBack && sureBack(ret);
        // })
        // .catch((err) => {
        //     console.log("出现异常回调失败------------------------------------------------");
        //     // failBack && failBack(err);
        // });

        Axios.post(`${uploadUrl}`, tformData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
          })
        .then((result) => {
            console.log("-----------------回调回来响应："+ JSON.stringify(result));
            let ret = result.data;
            if (data["autoShowWait"]) {
                Toast.clear();
            }
            console.log("-----------------回调回来响应11："+ JSON.stringify(ret));
            console.log("-----------------回调回来响应12："+ JSON.stringify(ret["code"]));
            try{  
              if(ret["code"] == -1) {
                console.log("-----------------回调回来响应13："+ JSON.stringify(ret));
                Notify({
                  type:"danger",
                  message:ret['msg']
                })
                failBack && failBack(ret);
              }else {
                ret["url"] = ret["url"];
                sureBack && sureBack(ret);
              }
             
            }catch(err){
              console.log("上传成功后，回调出现异常", err)
            }
            
        })
        .catch((err) => {
            console.log("出现异常回调失败------------------------------------------------");
            failBack && failBack(err);
        });

    }

  }

  /**
   * 多图上传
   * @param dataList 数据源
   * @param sureBack 成功回调
   */
  multiUpload (dataList, sureBack, autoShowWait, failCallBack) {
    if (!Vue.prototype.$dealMsg("UPLOAD_URL")) {
        sureBack && sureBack([]);
        return;
    }
    if (autoShowWait) {
      Toast.loading({
        duration: 0,
        message: "加载中...",
        forbidClick: true
      });
    }

    /// 每次多图上传队列置空
    this.uploadedList = [];
    if (dataList.length == 0) {
      sureBack && sureBack([]);
      return;
    }


    for (var i = 0; i < dataList.length; i++) {
      /// 闭包图片上传 filePath
      var doUPload = (data, i, length, sureBack) => {
        this.upload({
          ...data,
          fileName: data["fileName"] || `${new Date().getTime()}`,
          base64URL: data["base64URL"],
          file: data["file"],
          moduleName: data["moduleName"],
        }, (ret) => {
          if (ret && ret["url"]) {
            console.log("返回结果：", ret);
            this.uploadedList[i] = ret["url"];;

            /// 上传队列长度不足，不比对
            if (this.uploadedList.length < length) {
              return;
            }
            console.log("-------------------------------上传队列结果判空");
            /// 上传队列结果判空
            var success = true;
            for (let item of this.uploadedList) {
              if (!item || item.length == 0) {
                success = false;
              }
            }

            /// 队列上传成功，返回
            if (success) {
              Toast.clear();
              sureBack && sureBack(this.uploadedList);
            }
          }
        },
        (ret) => {
            /// 上传失败重新上传
            console.log("上传失败, 重新提交上传i:" + i);
            console.log("上传失败, 重新提交上传i:" + (ret["code"] == -1));
            // if(ret["code"] == -1) {
              failCallBack && failCallBack(ret);
            // }else {
            //   doUPload(data, i, length, sureBack);
            // }
            
          }
        );
      };
      console.log("提交上传i:" + i);
      doUPload(dataList[i], i, dataList.length, sureBack);
    }
  }

  dataURLtoFile (dataURI, type) {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/png' });
  }
  base64toFile (dataurl) {
    const arr = dataurl.split(",");
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    } 
    return new Blob([u8arr], {
      type: mime
    });
  }

  async dataURLtoBlob (dataurl) {
    const arr = dataurl.split(",");
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }

    return new Blob([u8arr], {
      type: mime
    });
  }
  readFile (file, callback) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      callback(e.target.result)
    }

  }

}
export {
  fileUploader
};
export default fileUploader
